package com.wpp.websocket.api;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.adapter.standard.StandardWebSocketSession;

import java.util.HashMap;
import java.util.Objects;
import java.util.Set;

/**
 * @author thisisit
 * @class: UserSession
 * @desc: TODO
 * @date: 2021/6/18 6:48
 */
@Data
@Accessors( chain = true )
public class UserSession implements Comparable<UserSession> {
    private String userId;
    private WebSocketSession session;
    private Long timeout = 0L;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        UserSession that = (UserSession) o;
        return Objects.equals(userId, that.userId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(userId);
    }

    public static void main(String[] args) {
        UserSessionPool pool = UserSessionPool.getInstance();

        StandardWebSocketSession connection1 = new StandardWebSocketSession(null, new HashMap<String, Object>() {
            {
                put("u1", "u1");
            }
        }, null, null);
        StandardWebSocketSession connection2 = new StandardWebSocketSession(null, new HashMap<String, Object>() {
            {
                put("u1", "u1111111");
            }
        }, null, null);
        StandardWebSocketSession connection3 = new StandardWebSocketSession(null, new HashMap<String, Object>() {
            {
                put("u2", "u222222222");
            }
        }, null, null);


        UserSession s1 = new UserSession().setUserId("u1").setSession(connection1);
        pool.add(s1);

        UserSession s2 = new UserSession().setUserId("u1").setSession(connection2);
        pool.add(s2);


        UserSession s3 = new UserSession().setUserId("u2").setSession(connection3);
        pool.add(s3);


        System.out.println(pool.size());
        System.out.println(pool.getOnlineUserIds());

        Set<UserSession> userSessions = pool.getUserSessions();

        for (UserSession userSession : userSessions) {
            System.out.println(userSession);
        }

    }

    @Override
    public int compareTo(UserSession o) {
        return timeout.compareTo(o.getTimeout());
    }
}
